package com.huafeng.Interceptors;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @author 花风
 * @date 2023/8/15 21:17
 * @Description 日志拦截器
 */
@Order(1)
@Aspect
@Component
public class LogInterceptor {
    private static final Logger log = LoggerFactory.getLogger(LogInterceptor.class);

    private static final StopWatch stopWatch = new StopWatch();

    private String requestId = null;

    @Before("execution(* com.huafeng.controller.*.*(..))")
    public void doInterceptor(JoinPoint joinPoint) {
        // 开始计时
        stopWatch.start();

        // 获取请求路径，并生成唯一id
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        requestId = UUID.randomUUID().toString().replaceAll("-", "");
        String requestURI = request.getRequestURI();

        // 获取请求参数
        Object[] args = joinPoint.getArgs();
        String requestParams = "[" + StringUtils.join(args,",") + "]";

        //输出日志
        log.info("request start, id：{}, path：{}, ip：{}, params：{}",requestId,requestURI,request.getRemoteHost(),requestParams);
    }

    @After("execution(* com.huafeng.controller.*.*(..))")
    public void doAfter(){
        stopWatch.stop();
        long totalTimeMillis = stopWatch.getTotalTimeMillis();
        log.info("request end, id：{}, cost：{}ms",requestId,totalTimeMillis);
    }
}
